package com.wxq.day0421.controller;

import com.wxq.day0421.MyConst;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author wxq
 * @Date 2021/4/22
 **/

@Controller
public class FileDownController {

    private static final Log log = LogFactory.getLog(FileDownController.class);

    /**
     * 显示要下载的文件
     */
    @RequestMapping("/showDownFiles")
    public String show(HttpServletRequest request, Model model) {
        //要从D盘upload中下载
        String realPath = MyConst.UPLOAD_FILE;
        //封装为file对象
        File file = new File(realPath);
        //获取该文件夹下的所有图片
        File[] files = file.listFiles();

        List<String> fileString = new ArrayList<>();
        for (File file1 : files) {

            fileString.add(file1.getName());

        }
        model.addAttribute("files", fileString);
        return "showDownFiles";
    }

    @RequestMapping("/down")
    public String dowm(String filename, HttpServletResponse response) throws IOException {

        //要下载的文件路径
        String aFilePath = null;
        //输入流
        FileInputStream in = null;
        //输出流
        ServletOutputStream out = null;

        aFilePath = MyConst.UPLOAD_FILE;

        out = response.getOutputStream();
        //设置下载文件使用的报头
        response.setHeader("Content-Type", "application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment;filename=" + toUTF8String(filename));

        in = new FileInputStream(aFilePath + "/"+filename);
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = in.read(bytes)) != -1 && in != null) {
            out.write(bytes, 0, len );


        }
        out.flush();
        out.close();
        in.close();
        return null;


    }

    /**
     * 下载保存时 中文文件名字符编码转换方法
     */
    public String toUTF8String(String str) {
        StringBuilder sb = new StringBuilder();
        int len = str.length();
        for (int i = 0; i < len; i++) {
            //取出字符串中的每一个字符
            char c = str.charAt(i);
            //Unicode码值 在0-255 不作处理
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                //将Unicode编码 转换为UTF-8编码
                byte b[];
                try {
                    b = Character.toString(c).getBytes("UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    b = null;
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0) {
                        //按位与操作，将两边的数字 转成二进制
                        k &= 255;
                    }
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }


}
